#include "StdAfx.h"
#include "PagedEntity.h"

using namespace std;

namespace FEngine
{

	PagedEntity::PagedEntity(const string& _fileName, const string& _textureName, bool _generateImpostor)
		: Entity(_fileName, _textureName)
	{
		mImpostorTexture = NULL;

		if (_generateImpostor)
		{
			// Calculate the size of the object
			float minX = sqrt(getAABB()->getMinPoint().x * getAABB()->getMinPoint().x);
			float maxX = sqrt(getAABB()->getMaxPoint().x * getAABB()->getMaxPoint().x);
			float minY = sqrt(getAABB()->getMinPoint().y * getAABB()->getMinPoint().y);
			float maxY = sqrt(getAABB()->getMaxPoint().y * getAABB()->getMaxPoint().y);
			float scaleZ = (minY > maxY) ? minY : maxY;
			mImpostorScale = Vector3((minX + maxX) / 2.0f, (minY + maxY) / 2.0f, 0);

			
			// TODO
			// Use the data from Entity to get the object
			// and make a RenderToTexture (maybe?) to generate a file
			// where the object is shot from multiples points of view

			if (D3DXCreateTextureFromFileEx(FEngine::CoreEngine::getInstance()->getDeviceInterface(), L"ImpostorTest.png", D3DX_DEFAULT, D3DX_DEFAULT, 
										D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, 
										NULL, NULL, &mImpostorTexture) != D3D_OK)
				throw FEngine::FEngineException("PagedEntity", "PagedEntity", "Cannot load the impostor texture file");
		}
	}

	PagedEntity::~PagedEntity()
	{
		if (mImpostorTexture)
			mImpostorTexture->Release();
	}

	void PagedEntity::getVertexBuffer(LPDIRECT3DVERTEXBUFFER9* _vb) const
	{
		*_vb = mVertexBuffer;
	}
	
	void PagedEntity::getIndexBuffer(LPDIRECT3DINDEXBUFFER9* _ib) const
	{
		*_ib = mIndexBuffer;
	}
	
	void PagedEntity::getTexture(LPDIRECT3DTEXTURE9* _texture) const
	{
		*_texture = mMeshTexture;
	}

	int PagedEntity::getNumberVertices() const
	{
		return mNumberVertices;
	}

	int PagedEntity::getNumberPrimitives() const
	{
		return mNumberPrimitives;
	}
	
	void PagedEntity::getImpostorTexture(LPDIRECT3DTEXTURE9* _texture) const
	{
		*_texture = mImpostorTexture;
	}

	Vector3 PagedEntity::getImpostorScale() const
	{
		return mImpostorScale;
	}

} // namespace FEngine
